<template>
  <div class="app-container flex-col" v-loading="pageLoading" :element-loading-text="loadingText">
    <div class="app-container " style="min-height:auto;overflow:auto" :fullscreen="true">
      <div class="p-20">
        <el-form ref="form" :model="initData" label-width="auto">
          <el-row>
            <el-col :span="12">
              <el-form inline>
                <div class="flex flex-center">
                  <label class="mr-15">线别</label>
                  <el-select class="mr-15 flex1" v-model="initData.line" placeholder="请选择" @change="lineChange">
                    <el-option v-for="l in lineOptions" :key="l.id" :value="l.id" :label="l.line_name"></el-option>
                  </el-select>
                  <label class="mr-15">工单</label>
                  <el-select class="mr-15 flex1" v-model="initData.mo" filterable remote :remote-method="getGdOptions"
                    @change="moChange">
                    <el-option v-for="(g,t) in moOptions" :key="t" :value="g" :label="g"></el-option>
                  </el-select>
                </div>
              </el-form>
            </el-col>
            <el-col :span="12">
              <emp-scan :data="initData" :focus.sync="empFocus" @onChange="afterScanEmp">
              </emp-scan>
            </el-col>
            <el-col :span="6">
              <el-form-item label="料号">
                <div class="flex flex-center">
                  <el-input class="mr-15" v-model="initData.lot" size="medium" disabled></el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="6">
              <el-form-item label="数量">
                <div class="flex flex-center">
                  <el-input-number class="mr-15 ml-20" v-model="initData.print_qty" style="width:100%" :step="1"
                    :step-strictly="true" :min="1" :precision="0" label="请输入打印数量"></el-input-number>
                </div>

              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label-width="80px">
                <el-button type="primary" @click="submit">标签打印</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div>
          <el-card class="box-card" style="margin-top:10px">
            <div slot="header" style="color:#fff;font-weight:600" class="clearfix">
              打印记录
            </div>
            <div class="filter-container fr">
              <span class="text-white t-16 mr-6 filter-item">起始条码</span>
              <el-input-number style="width:200px" class="mr-6 filter-item" min="1" v-model="query.start"
                placeholder="起始">
              </el-input-number>
              <span class="text-white t-16 mr-6 filter-item">结束条码</span>
              <el-input-number style="width:200px" class="filter-item" min="1" v-model="query.end" placeholder="结束">
              </el-input-number>
              <el-button class="filter-item" type="warning" @click="openModal" style="margin-left:30px">标签补印</el-button>
            </div>
            <el-table v-loading="tableLoading" :data="list" style="width: 100%" :border="true">
              <!-- <el-table-column type="selection" width="55"></el-table-column> -->
              <el-table-column v-for="(v,index) in columns" :label="v.title" :prop="v.key" :width="v.width"
                :key="index">
              </el-table-column>
            </el-table>
            <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
              @change="getList"></z-pagination>
          </el-card>
          <el-dialog :title="'补印--请输入账号密码'" width="40%" :close-on-click-modal="false" :visible.sync="editFormVisible">
            <div>
              <el-form ref="form" :model="reprintingData" label-width="50px">
                <el-form-item label="账号">
                  <el-input type="text" ref="inputName" v-model="reprintingData.user_id"
                    @keyup.enter.native="nextInput">
                  </el-input>
                </el-form-item>
                <el-form-item label="密码" class="mt-10">
                  <el-input type="password" ref="password" v-model="reprintingData.password"
                    @keyup.enter.native="reprinting"></el-input>
                </el-form-item>
              </el-form>
              <div class="text-right" style="margin-top:30px">
                <el-button @click="editFormVisible = false">取消</el-button>
                <el-button type="primary" :loading="reprintLoading" @click="reprinting()">补印</el-button>
              </div>
            </div>
          </el-dialog>
        </div>
      </div>

    </div>
    <message-box :msgs="msgs"></message-box>

  </div>
</template>

<script>
import mixinClient from '@/views/_common/mixinClient'
import messageBox from '@/components/WinClient/messageBox'

import zPagination from '@/views/_common/pagination'
import _ from 'lodash'
import { fileUrl } from '@/utils/index.js'
import empScan from '@/components/WinClient/empScan'
import lineGroup from '@/components/WinClient/lineGroup'

export default {
  name: 'codePrint',
  mixins: [mixinClient],
  components: { zPagination, empScan, messageBox, lineGroup },
  data() {
    return {
      reprintLoading: false,
      tableLoading: false,
      tabelHeight: 'auto',
      loadingText: '',
      lineOptions: [],
      columns: [
        { title: '机种', key: 'type_name', width: 120 },
        { title: '产品编号', key: 'serial_number', width: 250 },
        { title: '品号简码', key: 'key_part_no', width: 180 },
        { title: '工单号', key: 'key_part_name', width: 180 },
        { title: '备注', key: 'vendor_code', width: 150 },
        { title: '是否打印', key: 'vendor_name', width: 150 },
        { title: '客户条码', key: 'date_code', width: 130 },
        { title: '客户料号', key: 'lot', width: 130 },
        { title: '客户', key: 'lot_qty', width: 110 },
      ],
      skuOptions: [],
      vendorOptions: [],
      data: { lot_qty: 1, print_qty: 1 },
      list: [],
      total: 0,
      pageLoading: false,
      query: {
        size: 10,
        page: 1,
        start: undefined,
        end: undefined,
        sn: '',
      },
      editFormVisible: false,
      reprintingData: { user_id: '', password: '', valueList: [] },
      pagination: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, jumper, ->, total, sizes',
      },
      initData: {
        mo: null,
        line: null,
      },
      empFocus: false,
      msgs: [],
      moOptions: [],
    }
  },
  watch: {
    'data.key_part_id': {
      handler: function (newData, oldData) {
        this.query.keyPartId = newData
      },
    },
    'data.vendor_id': {
      handler: function (newData, oldData) {
        this.query.vendorId = newData
      },
    },
  },
  created() {
    this.$request(this.$api.line + 'getlistbypage', {}, 'get', true)
      .then((r) => {
        this.lineOptions = r.list
      })
      .catch(() => {})
  },
  methods: {
    checkData() {
      if (!this.initData.emp) {
        this.showMessage('请扫描作业员')
        this.empFocus = true
        return
      }
      if (this.initData.emp && !this.initData.empName) {
        this.showMessage('作业员错误', true)
        return
      }
      if (this.initData.puzzleNum) {
        this.canScan = true
        setTimeout(() => {
          this.showMessage('请扫描序号', false)
          this.$refs.scan.focus()
        }, 200)
      } else {
        this.$refs.puzzleNum.select()
        this.showMessage('请设置拼板数量')
      }
    },
    afterScanEmp(r) {
      if (r) {
        if (!this.initData.line) {
          return this.showMessage('请选择线别')
        }
      } else {
        this.showMessage('作业员不正确', true)
      }
    },
    lineChange() {
      this.initData.mo = null
      this.moInfo = {}
      this.getGdOptions()
    },
    getGdOptions(value) {
      this.moOptions = []
      this.$request(this.$api.bindsn + 'MoQueryByLine', {
        lineid: this.initData.line,
        mo: value || '',
      }).then((r) => {
        this.moOptions = r
      })
    },
    moChange() {},
    research() {
      this.getList()
    },
    reset() {
      this.query = { size: 10, page: 1 }
      this.getList()
    },
    nextInput() {
      this.$refs.password.focus()
    },
    openModal() {
      this.reprintingData.user_id = ''
      this.reprintingData.password = ''
      console.log(this.query, 'this.query')
      if (!this.query.start && !this.query.end) {
        this.$message.error('请选择打印区间')
        return
      }
      this.editFormVisible = true
      this.$nextTick(() => {
        this.$refs.inputName.focus()
      })
    },
    // select(v) {
    //   this.reprintingData.valueList = []
    //   if (!v || v.length <= 0) return
    //   this.reprintingData.key_part_id = v[0].key_part_id
    //   v.forEach((v) => {
    //     this.reprintingData.valueList.push(v.id)
    //   })
    // },

    getMatOptions(query) {
      this.skuOptions = []
      if (query) {
        this.$request(this.$api.mat + 'getmatandsku', { queryString: query }).then((r) => {
          this.skuOptions = this.arrayOptions(r, 'id', ['key_part_no', 'key_part_name'])
        })
      }
    },
    getVendorOptions(query) {
      this.skuOptions = []
      if (query) {
        this.$request(this.$api.vendor + 'getlist', { queryString: query, size: 100, page: 1 }).then((r) => {
          this.vendorOptions = this.arrayOptions(r.list, 'id', ['vendor_code', 'vendor_name'])
        })
      }
    },

    arrayOptions(arr, v, l, text) {
      let r = []
      // 有text 并且text为数组
      if (text && !Array.isArray(text)) {
        console.error('text参数必须为数组且顺序和label参数一致')
        return false
      }
      if (!text) {
        text = []
      }
      arr.forEach((item) => {
        let data = ''
        if (!l) {
          data = item[v]
        } else if (Array.isArray(l)) {
          l.forEach((vtmp, index) => {
            data = data + ' ' + (text[index] ? text[index] : '') + item[vtmp]
          })
        } else {
          data = item[l]
        }
        if (item[v]) r.push({ value: item[v], label: data })
      })
      return r
    },

    getList() {
      this.tableLoading = true
      this.query.start = ''
      this.query.end = ''
      this.$request(this.$api.materialprint + 'getlist', this.query)
        .then((r) => {
          this.list = r.list
          this.list.forEach((v) => {
            v.type_name = v.type == 1 ? '正常打印' : '标签补印'
          })
          this.total = r.total
        })
        .finally(() => {
          this.tableLoading = false
        })
    },

    submit() {
      this.loadingText = '正在打印中'
      this.pageLoading = true
      this.data.size = this.query.size
      this.data.page = this.query.page
      this.$request(this.$api.materialprint + 'generateprintdata', this.data, 'post')
        .then((r) => {
          this.getList()
          if (window.electron) {
            window.electron
              .print([
                {
                  fileUrl: fileUrl(this.$api.baseUrl, r.labelData.temp_url),
                  fileName: '',
                  label_qty: r.labelData.label_qty,
                  content: r.labelData.data_content,
                  directory: this.functionName,
                  soft_type: r.labelData.soft_type,
                },
              ])
              .then((r) => {
                this.clear()
                this.$message.success('打印成功')
                this.pageLoading = false
              })
              .catch((e) => {
                this.$message.error(e.toString())
                this.pageLoading = false
              })
          } else {
            this.pageLoading = false
          }
        })
        .catch((e) => {
          console.log(e.toString())
          this.pageLoading = false
        })
    },
    reprinting() {
      let data = { ...this.reprintingData }
      if (!data.user_id || !data.password) {
        this.$message.error('账号、密码不能为空。')
        return
      }
      this.reprintLoading = true
      this.$request(this.$api.materialprint + 'reprinting', data, 'post')
        .then((r) => {
          if (!r || r.length <= 0) {
            this.$message.error('未获取到打印数据。')
            this.pageLoading = false
            return
          }
          this.editFormVisible = false
          this.reprintLoading = false
          if (window.electron) {
            this.loadingText = '正在补印中'
            this.pageLoading = true
            let tmp = []
            r.forEach((v) => {
              tmp.push({
                fileUrl: fileUrl(this.$api.baseUrl, v.temp_url),
                fileName: '',
                label_qty: 1,
                content: v.data_content,
                directory: this.functionName,
                soft_type: v.soft_type,
              })
            })
            window.electron
              .print(tmp)
              .then((r) => {
                this.getList()
                this.reprintingData.valueList = []
                this.$message.success('补印成功')
                this.pageLoading = false
              })
              .catch((e) => {
                this.$message.error(e.toString())
                this.pageLoading = false
              })
          } else {
            this.reprintingData.valueList = []
            this.getList()
          }
        })
        .catch((e) => {
          this.reprintLoading = false
        })
    },
    clear() {
      this.data.date_code = ''
      this.data.lot = ''
      this.data.lot_qty = 1
      this.data.print_qty = 1
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/client.scss';
.z-panel-body .col-left {
  text-align: right;
  margin-bottom: 25px;
}
::v-deep .el-col {
  margin-bottom: 10px;
}
::v-deep .el-card {
  background: none;
  //   border: 1px solid #409eff;
}
::v-deep .el-card__header {
  //   background: #409eff;
  background: #333333;
}
::v-deep .el-card__header {
  padding: 10px 20px;
}
::v-deep .el-date-editor {
  height: 42px !important;
  background: #333;
}
::v-deep .el-range-input {
  border-top: 1px solid;
  border-bottom: 1px solid;
  font-size: 20px;
}
::v-deep .el-range-separator {
  color: #fff;
  line-height: 42px;
  height: 42px;
}
::v-deep .el-pagination {
  height: 42px;
}
::v-deep .el-pagination button {
  background: #333;
  height: 42px;
  line-height: 42px;
}
::v-deep .el-pagination button .number {
  background: #333;
}
::v-deep .el-pagination__rightwrapper {
  height: 42px;
  line-height: 42px;
}
::v-deep .el-pagination__total {
  background: #333;
  height: 42px !important;
  line-height: 42px !important;
  font-size: 20px !important;
  color: #fff;
}
::v-deep .el-pagination__jump {
  background: #333;
  height: 42px !important;
  line-height: 42px !important;
  font-size: 20px !important;
  color: #fff;
}
::v-deep .el-pager li {
  background: #333;
  color: #fff;
  height: 42px;
  line-height: 42px;
  font-size: 20px;
}

.z-panel-body .col-right {
  text-align: left;
  padding-left: 20px;
}
::v-deep .el-button:hover,
.el-button:focus {
  background: #333;
  border-color: #dcdfe6;
  color: #409eff;
}
::v-deep .el-input__inner {
  font-size: 20px !important;
}
::v-deep .el-dialog__body {
  background: #333;
  color: #fff;
}
::v-deep .el-dialog__header {
  background: #333;
  color: #fff;
}
</style>
